package com.imoblife.brainwavestus.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Set;

import org.apache.http.protocol.HTTP;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.googleplay.billing.Consts;
import com.imoblife.brainwavestus.BrainWavestusApplication;
import com.imoblife.brainwavestus.LaunchScreenActivity;
import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.TestimonialsActivity;
import com.imoblife.brainwavestus.customview.DisplayPrewWindows;
import com.imoblife.brainwavestus.obpurchaseSystem.BaseOnPurchaseMarketBilling;
import com.imoblife.brainwavestus.obpurchaseSystem.BaseOnPurchaseMarketBilling.MarketBillingPurchaseNotific;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem.OBPurchaseNotifier;
import com.imoblife.brainwavestus.obpurchaseSystem.PriceManager;
import com.imoblife.brainwavestus.oldDownloadFrame.Commmand;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItem;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItem.DownLoadingListener;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItemPragrame;
import com.imoblife.brainwavestus.oldMedia.MediaplayerFactory;
import com.imoblife.brainwavestus.product.Store;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;
import com.imoblife.brainwavestus.tapjoy.TapjoyConstants;
import com.imoblife.brainwavestus.user.User;
import com.imoblife.brainwavestus.users.HttpServerConnectionUtil;
import com.imoblife.brainwavestus.util.AlertDialogUtil;
import com.imoblife.brainwavestus.util.BitMapFlyweightFactory;
import com.imoblife.brainwavestus.util.DBUtil;
import com.imoblife.brainwavestus.util.DebugUtil;
import com.imoblife.brainwavestus.util.DownloadUtil;
import com.imoblife.brainwavestus.util.MakePurchaseStateChenge;
import com.imoblife.brainwavestus.util.ProductUtil;


public class PurchaseProduct{

	private static final String TAG = "PurchaseProduct";
	Bitmap mBitmap;
	private Activity mActivity;
	private Store mStore;
	private User mUser;
	private DBUtil mDb;
	
	private class PurchaseItemInfo {

		String mName; // 曲目名称
		String mTaskName;// 任务名
		String mPrice;// 价格
		String mPirceTemp;
		Button mBuyButton;// 购买
		Button mFreeGet;// 免费获取
		CheckBox mPrewBox;// 预览
		ProgressBar mDownloadBar;// 下载进度
		TextView mDownloadtext; // 下载信息
		View mItemView;//

		int mTaskState;

		public PurchaseItemInfo() {

			if (LaunchScreenActivity.IS_PAD) {
				mItemView = mActivity.getLayoutInflater().inflate(
						R.layout.tb_brainwave, null);
			} else {
				mItemView = mActivity.getLayoutInflater().inflate(
						R.layout.brainwave, null);
			}

			mDownloadBar = (ProgressBar) mItemView
					.findViewById(R.id.download_progress);
			System.out.println("mDownloadBar>>" + mDownloadBar);
			mDownloadtext = (TextView) mItemView
					.findViewById(R.id.download_text);
			mBuyButton = (Button) mItemView.findViewById(R.id.buy);
			mFreeGet = (Button) mItemView.findViewById(R.id.getfree);
			mPrewBox = (CheckBox) mItemView.findViewById(R.id.playcheck);

		}

		private void setPurchaseAction() {

			DebugUtil.debug(TAG, "setPurchaseAction>>" + mTaskName + ".music");

			if (isPakage()) {
				showSubscriptionDialog();
				// mBaseOnPurchaseMarketBilling.requestPurchase(mTaskName,Consts.ITEM_TYPE_INAPP);
			}

			int taskState = DownLoadSchedulerSystem.getDownloadTaskState(
					mTaskName + ".music", mActivity);

			switch (taskState) {

			case DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE: {
				// mBaseOnPurchaseMarketBilling.requestPurchase(mTaskName,Consts.ITEM_TYPE_INAPP);
				showSubscriptionDialog();
			}
				break;

			case DownLoadItemPragrame.DOWN_STATE_FAILE: {
				Commmand.makeMusicDownloadCommand(mTaskName + ".music",
						mActivity);
				mHandler.postDelayed(new Runnable() {

					public void run() {
						updateUI();
					}
				}, 100);
			}
				break;
			case DownLoadItemPragrame.DOWN_STATE_CANCEL: {
				Commmand.makeMusicDownloadCommand(mTaskName + ".music",
						mActivity);
				mHandler.postDelayed(new Runnable() {
					public void run() {
						updateUI();
					}
				}, 100);

			}
				break;
			case DownLoadItemPragrame.DOWN_STATE_END: {

				AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
				builder.setTitle(R.string.redownloadtitle);
				builder.setMessage(R.string.redownloadmassege);
				builder.setNeutralButton(R.string.ok,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								Commmand.makeMusicReDownLoadCommand(mTaskName
										+ ".music", mActivity);
								mHandler.postDelayed(new Runnable() {
									public void run() {
										updateUI();
									}
								}, 100);

							}
						});
				builder.setNegativeButton(R.string.cancel, null);
				builder.show();

			}
				break;

			case DownLoadItemPragrame.DOWN_STATE_START: {

				((View) (mDownloadBar.getParent())).setVisibility(View.GONE);
				mBuyButton.setText(R.string.downLoad);
				Commmand.makeMusicCancalCommand(mTaskName + ".music", mActivity);
				mHandler.postDelayed(new Runnable() {
					public void run() {
						updateUI();
					}
				}, 100);
			}

				break;

			}

		}

		public void parserXML(XmlPullParser xp) throws XmlPullParserException,
				IOException {
			for (int i = 0; i < xp.getAttributeCount(); i++) {

				if ("brainstate".equals(xp.getAttributeName(i))) {

					TextView brainstate_text = (TextView) mItemView
							.findViewById(R.id.brainstate_text);
					brainstate_text.setText(xp.getAttributeValue(i));

				} else if ("description".equals(xp.getAttributeName(i))) {

					TextView description_text = (TextView) mItemView
							.findViewById(R.id.description_text);
					description_text.setText(mActivity.getResources()
							.getString(R.string.description)
							+ xp.getAttributeValue(i));

				} else if ("length".equals(xp.getAttributeName(i))) {

					TextView length_text = (TextView) mItemView
							.findViewById(R.id.length_text);
					length_text.setText(xp.getAttributeValue(i));

				} else if ("name".equals(xp.getAttributeName(i))) {

					TextView name = (TextView) mItemView
							.findViewById(R.id.name);
					String str = xp.getAttributeValue(i);
					mName = str;
					name.setText(str);

				} else if ("price".equals(xp.getAttributeName(i))) {

					mPrice = xp.getAttributeValue(i);
					mPirceTemp = mPrice;
					TextView price_text = (TextView) mItemView
							.findViewById(R.id.price_text);

					String newPrice = PriceManager.getProductPrice(mActivity,
							mTaskName, mPrice);
					if (!newPrice.equals(mPrice)) {

						TextView odlePrice = (TextView) mItemView
								.findViewById(R.id.odle_price);
						odlePrice.setText(mPrice);
						((View) odlePrice.getParent())
								.setVisibility(View.VISIBLE);
						mPrice = newPrice;
					}
					price_text.setText(newPrice);
					TextView tusprice = (TextView) mItemView
							.findViewById(R.id.tus_price_text);
					tusprice.setText(PriceManager.getTUSGold(mPrice));

				} else if ("id".equals(xp.getAttributeName(i))) {
					mTaskName = xp.getAttributeValue(i);
					if (PriceManager.getTaskName(mActivity, mTaskName)) {
						String newPrice = PriceManager.getProductPrice(
								mActivity, mTaskName, mPrice);
						TextView price_text = (TextView) mItemView
								.findViewById(R.id.price_text);
						TextView odlePrice = (TextView) mItemView
								.findViewById(R.id.odle_price);
						odlePrice.setText(mPrice);
						mPirceTemp = mPrice;
						mPrice = newPrice;
						((View) odlePrice.getParent())
								.setVisibility(View.VISIBLE);
						price_text.setText(newPrice);
						TextView tusprice = (TextView) mItemView
								.findViewById(R.id.tus_price_text);
						tusprice.setText(PriceManager.getTUSGold(newPrice));
					}
				}
			}
		}

		public void setAction() {
			mPrewBox.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					TextView name = (TextView) mItemView
							.findViewById(R.id.name);

					if (checkPlay()) {
						mPrewBox.setChecked(false);
						return;
					}
					new DisplayPrewWindows(mPrewBox, mActivity, mTaskName, name
							.getText().toString());

				}
			});
			mFreeGet.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					TextView name = (TextView) mItemView
							.findViewById(R.id.name);
					if (Integer.parseInt(VERSION.SDK) < 8
							) {

						if (checkPlay()) {
							return;
						}
					}
					showGetFreeDialog(name.getText().toString(), mPrice,
							mTaskName);
				}
			});

			mBuyButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					if (Integer.parseInt(VERSION.SDK) < 8
							) {

						if (checkPlay()) {
							return;

						}

					}
					setPurchaseAction();

				}
			});

		}

		Dialog subscrDialog;
		View purchaseSubScrButton;
		LinearLayout buyButton;
		TextView musicName;
		TextView musicPrice;

		private boolean checkPlay() {

			try {
				if (new MediaplayerFactory(mActivity).getBackgoundMediaPlayer()
						.isPlaying()) {
					new AlertDialogUtil(mActivity).showAlertDialog(
							mActivity.getResources().getString(
									R.string.alertutil_title),
							mActivity.getResources().getString(
									R.string.alertutil_content_stopmusic),
							mActivity.getResources().getString(
									R.string.alertutil_dismiss));

					return true;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return false;

		}

		public void showSubscriptionDialog() {

			SharedPreferences preferences = mActivity.getSharedPreferences(
					"configure", 0);

			if (preferences.getInt("configure", 0) == 0) {

				subscrDialog = new Dialog(mActivity, R.style.dialog);
				subscrDialog.addContentView(mActivity.getLayoutInflater()
						.inflate(R.layout.purchase_subscription_dialog, null),
						new LayoutParams(LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT));
				subscrDialog.setCancelable(true);
				subscrDialog.show();

				ImageView icon = (ImageView) subscrDialog
						.findViewById(R.id.icon);
				icon.setImageBitmap(mBitmap);
				purchaseSubScrButton = subscrDialog
						.findViewById(R.id.subscr_button);
				buyButton = (LinearLayout) subscrDialog
						.findViewById(R.id.buy_button);
				musicName = (TextView) subscrDialog
						.findViewById(R.id.music_name);
				musicPrice = (TextView) subscrDialog
						.findViewById(R.id.music_price);
				musicName.setText(mName);
				musicPrice.setText(mActivity.getResources().getString(
						R.string.purchase_button_price)
						+ " "
						+ mPrice
						+ " "
						+ mActivity.getResources().getString(
								R.string.purchase_usd));
				buyButton.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						mBaseOnPurchaseMarketBilling.requestPurchase(mTaskName,
								Consts.ITEM_TYPE_INAPP);
						subscrDialog.dismiss();
					}
				});
				purchaseSubScrButton.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						mBaseOnPurchaseMarketBilling.requestPurchase(
								MakePurchaseStateChenge.subscription_id,
								Consts.ITEM_TYPE_SUBSCRIPTION);
						subscrDialog.dismiss();
					}
				});
			} else {
				mBaseOnPurchaseMarketBilling.requestPurchase(mTaskName,
						Consts.ITEM_TYPE_INAPP);

			}

		}

		private void showGetFreeDialog(String title, final String price,
				final String taskName) {

			DebugUtil.debug(TAG, "购买意图>>" + taskName);

			String message = mActivity.getString(R.string.get_free_massge)
					+ " " + title + " (" + PriceManager.getTUSGold(price) + " "
					+ mActivity.getString(R.string.buy_tus_credits) + ")?";

			new AlertDialog.Builder(mActivity)
					.setMessage(message)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									OBpurchaseSystem.getOBpurchaseSystem(
											mActivity).purchaseProduct(
											taskName, new OBPurchaseNotifier() {
												public void noticeSuccess(
														String productId) {
													
													mUser.getLocalLib().addProduct(
															mStore.getProductByName(taskName));
													
													DownloadUtil.beginDownloadProduct(mActivity,
															mStore, 
															taskName
															);					
													mHandler.postDelayed(
															new Runnable() {
																public void run() {
																	updataPurchaseList();
																}
															}, 10);
													OBpurchaseSystem
															.getOBpurchaseSystem(
																	mActivity)
															.updateTapPoints();
													DebugUtil.debug(TAG, "taskName="
															+ taskName + "购买成功");
												}

												public void noticeFailed(
														String errorInfo) {
													DebugUtil.debug(TAG, errorInfo
															+ "购买失败");
												}
											}, mActivity);
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).show();

		}

		/**
		 * 刷新UI
		 */
		public void updateUI() {

			if (isPakage()) {
				DebugUtil.debug(TAG, "item info >>  合集信息");
				return;
			}

			DebugUtil.debug(TAG, "item info >>  updateUI");

			mTaskState = DownLoadSchedulerSystem.getDownloadTaskState(mTaskName
					+ ".music", mActivity);

			switch (mTaskState) {

			case DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE: {

				mBuyButton.setText(R.string.purchased);
				((View) mDownloadBar.getParent()).setVisibility(View.GONE);
				mFreeGet.setVisibility(View.VISIBLE);
			}
				break;
			case DownLoadItemPragrame.DOWN_STATE_END: {
				if (getPlayTaskName().equals(mTaskName)) {
					mBuyButton.setText(R.string.playing);
					mBuyButton.setEnabled(false);
				} else {
					mBuyButton.setText(R.string.reDownload);
					mBuyButton.setEnabled(true);
				}

				((View) mDownloadBar.getParent()).setVisibility(View.GONE);
				mFreeGet.setVisibility(View.GONE);

			}
				break;

			case DownLoadItemPragrame.DOWN_STATE_CANCEL: {

				mBuyButton.setText(R.string.download);
				((View) mDownloadBar.getParent()).setVisibility(View.GONE);
				mFreeGet.setVisibility(View.GONE);

			}
				break;

			case DownLoadItemPragrame.DOWN_STATE_FAILE: {

				((View) mDownloadBar.getParent()).setVisibility(View.VISIBLE);
				mBuyButton.setText(R.string.retry);
				mDownloadBar.setMax(100);
				float progress = DownLoadSchedulerSystem.getProgressDownload(
						mTaskName + ".music", mActivity);
				System.out.println("progress = " + progress);

				int stateExtr = mDb.openForRead().getDownFileRspCode(mTaskName);
				mDb.closeDb();
				
				if (stateExtr == DownLoadItemPragrame.EXTR_FAILE_SDCARDE) {
					mDownloadtext.setText((int) progress + "."
							+ ((int) (progress * 100)) % 100 + "%" + "--"
							+ mActivity.getString(R.string.sdcard_error_extr));
				} else if (stateExtr == DownLoadItemPragrame.EXTR_FAILE_NET) {
					mDownloadtext.setText((int) progress + "."
							+ ((int) (progress * 100)) % 100 + "%" + "--"
							+ mActivity.getString(R.string.net_error_extr));

				}

				mDownloadBar.setProgress((int) (progress + 0.5));
				mFreeGet.setVisibility(View.GONE);

			}
				break;
			case DownLoadItemPragrame.DOWN_STATE_START: {
				((View) mDownloadBar.getParent()).setVisibility(View.VISIBLE);
				mBuyButton.setText(R.string.cancel);
				mDownloadBar.setMax(100);
				float progress = DownLoadSchedulerSystem.getProgressDownload(
						mTaskName + ".music", mActivity);
				String wait = mActivity.getString(R.string.wait);
				mDownloadtext.setText((int) progress + "."
						+ ((int) (progress * 100)) % 100 + "%" + "--" + wait);
				mDownloadBar.setProgress((int) (progress + 0.5));
				DebugUtil.debug(TAG, mTaskName + "progress>>"
						+ ((int) (progress + 0.5)));
				mFreeGet.setVisibility(View.GONE);
			}
				break;

			default:
				break;
			}

		}

		/**
		 * 判断 是否为合集信息
		 * 
		 * @return
		 */
		private boolean isPakage() {
			if (hashMap.size() < 2) {
				return false;
			}
			if (mProductId.equals(mTaskName)) {
				return true;
			}
			return false;
		}

	}

	private class PurchaseProductInfo extends PurchaseItemInfo {

		public PurchaseProductInfo() {
			super();

		}

		public void parserXML(XmlPullParser xp) throws XmlPullParserException,
				IOException {

			for (int i = 0; i < xp.getAttributeCount(); i++) {

				if (xp.getAttributeName(i).equals("title")) {

					((TextView) mActivity.findViewById(R.id.title)).setText(xp
							.getAttributeValue(i));

				} else if (xp.getAttributeName(i).equals("brainstate")) {

					TextView brainstate_text = (TextView) mItemView
							.findViewById(R.id.brainstate_text);
					brainstate_text.setText(xp.getAttributeValue(i));

				} else if (xp.getAttributeName(i).equals("description")) {

					TextView description_text = (TextView) mItemView
							.findViewById(R.id.description_text);
					description_text.setText(mActivity.getResources()
							.getString(R.string.description)
							+ xp.getAttributeValue(i));

				} else if (xp.getAttributeName(i).equals("length")) {
					TextView length_text = (TextView) mItemView
							.findViewById(R.id.length_text);
					length_text.setText(xp.getAttributeValue(i));
				} else if (xp.getAttributeName(i).equals("price")) {

					mPrice = xp.getAttributeValue(i);
					TextView price_text = (TextView) mItemView
							.findViewById(R.id.price_text);

					String newPrice = PriceManager.getProductPrice(mActivity,
							mProductId, mPrice);
					if (!newPrice.equals(mPrice)) {

						TextView odlePrice = (TextView) mItemView
								.findViewById(R.id.odle_price);
						odlePrice.setText(mPrice);
						((View) odlePrice.getParent())
								.setVisibility(View.VISIBLE);
						mPrice = newPrice;
					}

					price_text.setText(newPrice);
					TextView tusprice = (TextView) mItemView
							.findViewById(R.id.tus_price_text);
					tusprice.setText(PriceManager.getTUSGold(mPrice));

				} else if (xp.getAttributeName(i).equals("name")) {
					TextView name = (TextView) mItemView
							.findViewById(R.id.name);
					mName = xp.getAttributeValue(i);
					name.setText(xp.getAttributeValue(i));
				} else if ("id".equals(xp.getName())) {
					mTaskName = xp.nextText();
				}

			}

		}

	}

	String mProductId;

	HashMap<String, PurchaseItemInfo> hashMap;

	Button review;

	Handler mHandler;

	BaseOnPurchaseMarketBilling mBaseOnPurchaseMarketBilling;
	
	public PurchaseProduct(Activity activity, Store store, String productId) {
		
		mActivity = activity;
		mUser = ((BrainWavestusApplication)activity.getApplication()).getUser();
		mStore = store;
		mProductId = productId;
		mDb = new DBUtil(mActivity);
		
		hashMap = new HashMap<String, PurchaseProduct.PurchaseItemInfo>();
		mHandler = new Handler();
		mBaseOnPurchaseMarketBilling = new BaseOnPurchaseMarketBilling(
				mActivity, mHandler, new MarketBillingPurchaseNotific() {

					public void success() {
						updataPurchaseList();
					}
				});
	}
	
	public PurchaseProduct(Activity activity) {
		
		
		hashMap = new HashMap<String, PurchaseProduct.PurchaseItemInfo>();
		mHandler = new Handler();
		mBaseOnPurchaseMarketBilling = new BaseOnPurchaseMarketBilling(
				mActivity, mHandler, new MarketBillingPurchaseNotific() {

					public void success() {
						updataPurchaseList();
					}
				});
	}

	public void loading() {
		try {
			initInfo();
		} catch (IOException e) {

			e.printStackTrace();
		} catch (XmlPullParserException e) {

			e.printStackTrace();
		}

		setPakagePrice();
	}

	private void addAnInfo(PurchaseItemInfo info) {

		if (info.mTaskName == null) {
			info.mTaskName = mProductId;
			hashMap.put(mProductId, info);
			View view = (View) info.mItemView.findViewById(R.id.length)
					.getParent();
			view.setVisibility(View.GONE);
			info.mItemView.setBackgroundColor(0x30ffffff);
			// info.mPrewBox.setVisibility(View.INVISIBLE);
			((LinearLayout) mActivity.findViewById(R.id.productItemLayout))
					.addView(info.mItemView);
		} else {
			hashMap.put(info.mTaskName, info);
			LinearLayout layout = ((LinearLayout) mActivity
					.findViewById(R.id.productItemLayout));
			layout.addView(info.mItemView, layout.getChildCount() - 1);
			hashMap.get(mProductId).mPrewBox.setVisibility(View.INVISIBLE);
		}

		info.setAction();
	}

	private String getPlayTaskName() {
		SharedPreferences preferences = mActivity.getSharedPreferences(
				"musicName", 0);
		return preferences.getString("playTaskName", "");

	}

	public void initInfo() throws IOException, XmlPullParserException {

		ImageView icon = (ImageView) mActivity.findViewById(R.id.icon);
		mBitmap = BitMapFlyweightFactory
				.getBitMapFlyweightFactory(mActivity.getAssets())
				.getBitMapFlyweight(mProductId).getBitmap();

		icon.setImageBitmap(mBitmap);

		XmlPullParser parser = Xml.newPullParser();

		InputStream fileInputStream = null;

		fileInputStream = mActivity.getAssets().open(
				"des/" + ProductUtil.getLang() + "/" + mProductId + ".xml");

		parser.setInput(fileInputStream, "UTF-8");

		while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {

			if (XmlPullParser.START_TAG == parser.getEventType()) {

				if ("brainwave".equals(parser.getName())) {
					PurchaseProductInfo info = new PurchaseProductInfo();
					info.parserXML(parser);
					addAnInfo(info);
				} else if ("item".equals(parser.getName())) {
					PurchaseItemInfo itemInfo = new PurchaseItemInfo();
					itemInfo.parserXML(parser);
					addAnInfo(itemInfo);
				} else if ("detail".equals(parser.getName())) {
					((TextView) mActivity.findViewById(R.id.detail))
							.setText(parser.nextText());
				}
			}
			parser.next();
		}

	}

	public void setAction() {

		initCommonAction();

		if (LaunchScreenActivity.IS_PAD) {

			initXlargeAction();

		} else {
			initNomalAction();
		}

	}

	private void initCommonAction() {
		review = (Button) mActivity.findViewById(R.id.review);
		review.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				mActivity.startActivity(new Intent(mActivity,
						TestimonialsActivity.class));

			}
		});
	}

	private void initXlargeAction() {

		RadioGroup swichGroup = (RadioGroup) mActivity
				.findViewById(R.id.tab_swich);
		swichGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {

				if (checkedId == R.id.radio_ins) {
					mActivity.findViewById(R.id.detail).setVisibility(
							View.VISIBLE);
					mActivity.findViewById(R.id.guarantee).setVisibility(
							View.GONE);
					review.setVisibility(View.GONE);

				} else {

					mActivity.findViewById(R.id.detail)
							.setVisibility(View.GONE);
					mActivity.findViewById(R.id.guarantee).setVisibility(
							View.VISIBLE);
					review.setVisibility(View.VISIBLE);
				}

			}
		});

	}

	private void initNomalAction() {

		final FrameLayout frameLayout = (FrameLayout) mActivity
				.findViewById(R.id.swich_view_flipper);

		TextView introduction_enter = (TextView) mActivity
				.findViewById(R.id.introduction_enter);
		TextView purchase_enter = (TextView) mActivity
				.findViewById(R.id.purchase_enter);
		TextView guarantee_enter = (TextView) mActivity
				.findViewById(R.id.guarantee_enter);

		introduction_enter.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				frameLayout.getChildAt(0).setVisibility(View.VISIBLE);
				frameLayout.getChildAt(1).setVisibility(View.GONE);
				frameLayout.getChildAt(2).setVisibility(View.GONE);
			}
		});

		purchase_enter.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				frameLayout.getChildAt(1).setVisibility(View.VISIBLE);
				frameLayout.getChildAt(0).setVisibility(View.GONE);
				frameLayout.getChildAt(2).setVisibility(View.GONE);
			}
		});

		guarantee_enter.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				frameLayout.getChildAt(2).setVisibility(View.VISIBLE);
				frameLayout.getChildAt(0).setVisibility(View.GONE);
				frameLayout.getChildAt(1).setVisibility(View.GONE);
			}
		});

	}

	/**
	 * 刷新购买列表
	 */
	public void updataPurchaseList() {

		Set<String> strings = hashMap.keySet();

		if (hashMap.size() == 1) {
			hashMap.get(mProductId).updateUI();
			return;
		}

		boolean gonePakageInfo = false;

		for (String string : strings) {

			if (!string.equals(mProductId)) {
				PurchaseItemInfo itemInfo = hashMap.get(string);
				itemInfo.updateUI();
				if (itemInfo.mFreeGet.getVisibility() != View.VISIBLE) {
					gonePakageInfo = true;
				}
			}
		}
		if (gonePakageInfo) {
			hashMap.get(mProductId).mItemView.setVisibility(View.GONE);
		}
	}

	/**
	 * 注册下载监听
	 */
	public void registerDownloadListner() {

		class ListenerDownload implements DownLoadingListener, Runnable {

			Handler handler = new Handler();
			PurchaseProduct.PurchaseItemInfo mPurchaseItemInfo;
			int extr;
			long progress;
			long size;
			int count = 0;

			public void run() {

				if (extr == DownLoadItemPragrame.EXTR_SUCC) {

					if (mPurchaseItemInfo.mTaskState == DownLoadItemPragrame.DOWN_STATE_FAILE) {
						mPurchaseItemInfo.updateUI();
					}

					if (count % 10 == 0) {

						mPurchaseItemInfo.mDownloadBar
								.setMax((int) (size / 100));
						mPurchaseItemInfo.mDownloadBar
								.setProgress((int) (progress / 100));

						float fomart = progress * 1.0f / size * 10000f;

						String sub = null;

						if ((int) (fomart % 100) >= 10) {
							sub = (int) (fomart % 100) + "%";
						} else {
							sub = "0" + (int) (fomart % 100) + "%";
						}

						mPurchaseItemInfo.mDownloadtext.setText((int) (progress
								* 1.0f / size * 100f)
								+ "." + sub);

					}
					count++;

					if (progress == size) {
						count = 0;
						handler.postDelayed(new Runnable() {
							public void run() {
								updataPurchaseList();
							}
						}, 1000);
					}
				} else {
					count = 0;
					handler.postDelayed(new Runnable() {
						public void run() {
							updataPurchaseList();
						}
					}, 1000);

					DebugUtil.debug(TAG, "下载失败>>" + mPurchaseItemInfo.mTaskName);

				}
			}

			public void downloading(String downlaodname, int extr,
					long progress, long size) {

				mPurchaseItemInfo = hashMap.get(downlaodname.replace(".music",
						""));

				if (mPurchaseItemInfo == null) {
					return;
				}

				this.extr = extr;
				this.progress = progress;
				this.size = size;
				handler.post(this);

			}

		}
		DownLoadItem.setDownLoadingListener(new ListenerDownload());

	}

	/**
	 * 取消下载监听
	 */

	public void unRegisterDownloadLister() {

		DownLoadItem.setDownLoadingListener(null);

	}

	/**
	 * 释放资源
	 */
	public void release() {
		mBaseOnPurchaseMarketBilling.destroy();
		BitMapFlyweightFactory.getBitMapFlyweightFactory(mActivity.getAssets())
				.requestRelease(mProductId);
		System.gc();

	}

	private void setPakagePrice() {
		PurchaseItemInfo pakege = null;
		Set<String> strings = hashMap.keySet();
		float totalPrice = 0;

		for (String string : strings) {
			PurchaseItemInfo itemInfo = hashMap.get(string);

			if (itemInfo.isPakage()) {
				pakege = itemInfo;
			} else {
				try {
					totalPrice += Float.parseFloat(itemInfo.mPirceTemp.replace(
							"$", "").replace(" ", ""));
				} catch (Exception e) {
				}
			}

		}

		if (pakege != null) {
			TextView odlePrice = (TextView) pakege.mItemView
					.findViewById(R.id.odle_price);
			DecimalFormat myFormatter = new DecimalFormat("####.##");
			odlePrice.setText("$ " + myFormatter.format(totalPrice));
			((View) odlePrice.getParent()).setVisibility(View.VISIBLE);
		}

	}

	public void sendPurchaseIdToServer(final String gmail, final String music,
			final String price) {
		dialog = new ProgressDialog(mActivity) {
			protected void onStop() {
				dialog = null;
				super.onStop();
			}
		};
		dialog.setMessage(mActivity.getResources().getString(
				R.string.processing_message));
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		final String urlPath = HttpServerConnectionUtil.SETMUISCBILL_PATH
				+ "?gmail=" + gmail + "&music=" + music + "&update=0";
		
		DebugUtil.debug(TAG, "request url: " + urlPath);
		new Thread(new Runnable() {
			public void run() {
				try {
					URL url = new URL(urlPath);
					HttpURLConnection connection = (HttpURLConnection) url
							.openConnection();
					connection.setConnectTimeout(10000);
					connection.setReadTimeout(10000);
					connection.setRequestProperty("Charset", "UTF-8");
					connection.connect();
					if (connection.getResponseCode() == 200) {
						BufferedReader br = new BufferedReader(
								new InputStreamReader(connection
										.getInputStream(), HTTP.UTF_8));
						StringBuilder builder = new StringBuilder();
						String line = null;
						while ((line = br.readLine()) != null) {
							builder.append(line);
						}
						String response = builder.toString();
						Log.v(TAG, "response = " + response);
						if (response.equals("1")) {
							String gold = String.valueOf(OBpurchaseSystem
									.getOBpurchaseSystem(mActivity)
									.getTapjoyPoints());
							int temp = Integer.parseInt(gold)
									- Integer.parseInt(price);
							Log.v(TAG, "gold = " + gold);
							Log.v(TAG, "temp = " + temp);
							setTapjoyPoints(temp);
							MakePurchaseStateChenge.confirmPurchaseState(
									mActivity, music);
							mHandler.postDelayed(new Runnable() {
								public void run() {
									updataPurchaseList();
								}
							}, 10);
							Looper.prepare();
							dialog.cancel();
							Looper.loop();
						} else if (response.equals("0")) {
							Looper.prepare();
							dialog.cancel();
							new AlertDialog.Builder(mActivity)
									.setMessage(
											mActivity
													.getResources()
													.getString(
															R.string.network_down_message))
									.setPositiveButton(
											R.string.retry,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													sendPurchaseIdToServer(
															gmail, music, price);
												}
											})
									.setNegativeButton(
											R.string.cancel,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
												}
											}).create().show();
							Looper.loop();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					Looper.prepare();
					Toast.makeText(
							mActivity,
							mActivity.getResources().getString(
									R.string.register_error_code_response),
							3000).show();
					dialog.cancel();
					Looper.loop();
				}
			}
		}).start();

	}

	ProgressDialog dialog;

	public void setTapjoyPoints(int points) {
		SharedPreferences settings = mActivity.getSharedPreferences(
				TapjoyConstants.TJC_PREFERENCE, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(TapjoyConstants.PREF_LAST_TAP_POINTS, points);
		editor.commit();
	}
}
